<template>
	<view class="order-detail-page">
		<!-- 导航栏 -->
		<!-- #ifndef MP-WEIXIN -->
		<free-nav-bar textContent="填写订单信息" isBackShow></free-nav-bar>
		<!-- #endif -->
		<view class="order-detail-wrapper">
			<view class="order-detail__top">
				<view class="order-detail__top--info flex">
					<view class="user__info flex">
						<view style="font-size: 18rpx;margin-right: 15rpx;display: flex;align-items: center;" v-if="currentAddress.defaultStatus">
							<uni-tag :mark="true" style="background-color: #FD5052 ;border-color:#FD5052 ;" text="默认" type="primary" size="mini" />
						</view>
						<view>
							<text class="main-text-color name">{{currentAddress.name}}</text>
							<text class="main-text-color phone">{{currentAddress.mobile}}</text>
							<view class="icon-item">
								<text class="uni-icons uniui-right" style="font-size: 30px;"></text>
							</view>
						</view>
					</view>
				</view>
				<view class="order-detail__top--address flex">					
					<uni-list style="width: 100%;" >
						<uni-list-item title="" style="width: 100%;"  clickable showArrow @click="changeAddress">	
							<template v-slot:header>								
								<view class="address_icon"><i style="width: 80rpx; height: 80rpx;" class="sprite sprite-position"></i></view>
							</template>
							<!-- 自定义 body -->
							<template v-slot:body>								
								<text v-if="currentAddress.detailAddress && currentAddress.detailAddress != ''" class="address__text main-text-color font28">{{currentAddress.detailAddress}}</text>
								<text v-else>请选择地址</text>
							</template>							
						</uni-list-item>
					</uni-list>
					<!-- <text class="address__text main-text-color font28">广东省深圳市南山区桃源街道平山村平山村110栋生活驿站便利店</text> -->
				</view>
			</view>
			<view class="order-detail__product" v-for="(orchard, index) in order.list" :key="orchard.name">
				<view class="shop-name">{{ orchard.name }}</view>
				<ul>
					<li class="flex" v-for="(item, k) in orchard.items" :key="item.id">
						<view class="order-detail__product--img">
							<image style="width: 100%; height: 100%;" :src="item.picUrl"/>
						</view>
						<view class="order-detail__product--info">
							<view class="info-warpper">
								<text class="title main-text-color font28">{{item.spuName}}</text>
								<text class="text__info">规格：{{getSkuName(item.properties)}}</text>
							</view>
							<view class="order-detail__price flex">
								<view class="order-detail__product--price flex">
									<text class="price"><span class="symbol">￥</span>{{parsePrice(item.price)}}</text>
								</view>
								<view class="quantity flex">
									<span class="reduce" @click="reduceHandle(item)"></span>
									<span class="number">{{item.count}}</span>
									<span class="add" @click="addBuyNumHandle(item)"></span>
								</view>
							</view>
						</view>
					</li>
				</ul>
			</view>
			<view class="order-detail__order">
				<view class="order__item flex">
					<view class="label">保障服务</view>
					<view class="val main-text-color" style="color: #FD5052;">坏果包换</view>
				</view>
				<view class="order__item flex">
					<view class="label">配送</view>
					<view class="val main-text-color">快递运输</view>
				</view>
				<view class="order__item flex">
					<view class="label">运费</view>
					<view class="val main-text-color" v-if="order.price && order.price.deliveryPrice && order.price.deliveryPrice > 0">￥{{parsePrice(order.price.deliveryPrice)}}</view>
					<view class="val main-text-color" v-else>￥0.00</view>
				</view>
				<view class="notes">
					<span class="notes-title">备注</span>
					<textarea class="notes-textarea" style="padding: 10rpx;" v-model="formData.remark" placeholder="请输入备注" cols="30" rows="3"></textarea>
				</view>
			</view>
			<view class="order-detail--btns__container">
				<view class="order-detail--btns flex">
					<span class="total-num">共{{formData.total}}件</span>
					<view class="total-price">
						<span class="total-price__text">共计：</span>
						<template v-if="order.price && order.price.payPrice && order.price.payPrice > 0">
							<span class="symbol" >￥</span>{{parsePrice(order.price.payPrice)}}
						</template>
						<template v-else><span class="symbol">￥</span>{{parsePrice(order.totalMoney)}}</template>
						
					</view>
					<view class="btn font28 flex" @click="submitOrder">下单并支付</view>
				</view>
			</view>
		</view>
		<uni-popup ref="addressPopup" type="bottom" borderRadius="10px 10px 0 0" background-color="#fff">
			<uni-list class="address_list" >
				<template v-if="myAddrList && myAddrList.length > 0">
					<uni-list-item v-for="item in myAddrList" title="" :key="item.id" class="address-detail" direction="column" clickable showArrow @click="selectHandle(item)">
						<template v-slot:header>
							<view class="slot-box">
								<text>{{item.name}}</text>
								<text style="margin-left: 20rpx;">{{item.mobile}}</text>	
							</view>											
						</template>
						<!-- 自定义 body -->
						<template v-slot:body>								
							<text class="main-text-color font28">{{item.detailAddress}}</text>
						</template>							
					</uni-list-item>
				</template>
				
				<uni-list-item title="" clickable>
					<template v-slot:body>
						<view class="add">
							<button class="add-address" type="warn" @click="goAddAddress">添加地址</button>
						</view>
					</template>	
				</uni-list-item>
			</uni-list>
		</uni-popup>
	</view>
</template>

<script>
	import $H from '@/common/free-lib/request.js';
	import $U from '@/common/free-lib/util.js';
	import freeNavBar from "@/components/free-ui/free-nav-bar.vue"
	export default {
		components: {
			freeNavBar
		},
		data() {
			return {
				cartList:[],
				orderItems: [],
				currentAddress: {
					areaId:0,
					id: 0,
					name: '',
					mobile: '',
					detailAddress: '',
					defaultStatus: false
				},
				order: {},
				formData: {
					items: [],
					total: 0,
					totalMoney: 0,
					remark: '',
					addressId: null,
					deliveryType: 1,
					pointStatus: false
				},
				myAddrList: []
			}
		},
		onLoad(e) {
			// console.log(e);
			if(e && e.items) {
				this.cartList = JSON.parse(e.items);
				this.getSettlement();
			}			
		},
		onShow() {
			this.getDefaultAddress();
			this.getMyAddressList()
		},
		created() {
			
		},
		methods: {
		  getSettlement() {
			  if(this.cartList && this.cartList.length > 0) {
				  let itemsList = []
				  this.cartList.forEach(cart => {
					  let item = {skuId: cart.sku.id, count: cart.count, cartId: cart.id}
					  itemsList.push(item)
				  })
				  let data = {itemList: JSON.stringify(itemsList), pointStatus:false, deliveryType: 1}
				  if(this.formData.addressId && this.formData.addressId > 0) {
					  data.addressId = this.formData.addressId;
				  }
				  let _this = this;
				  //获取结算信息（订单支付金额，邮费）
				  $H.get('/trade/order/getSettlement', data).then(res => {
				  	if(res) {
						_this.order = res;
				  		_this.buildFormData();
				  	}
				  })
			  }
			 
		  },	
		  submitOrder() {
			  this.formData.addressId = this.currentAddress.id;
			  if(this.validateForm()) {
				  let openid = $U.getOpenId();
				  if(openid) {
					  uni.showLoading({title: '加载中，请稍后'});
					  $H.post('/trade/order/create', this.formData).then(res => {
						if(res) {
							let extras = {openid};
							let orderId = res.id;
							$H.post('/pay/order/submit', {id: res.payOrderId, channelCode: 'wx_lite', channelExtras: extras}).then(res => {
								if(res && res.status == 0) {
									uni.hideLoading();
									let payData = JSON.parse(res.displayContent);
									uni.requestPayment({
									    provider: 'wxpay',
										timeStamp: payData.timeStamp,
										nonceStr: payData.nonceStr,
										package: payData.packageValue,
										signType: payData.signType,
										paySign: payData.paySign,
										success: function (res) {
											uni.navigateTo({url: '/pages/common/payment-success?orderId=' + orderId});
										},
										fail: function (err) {
											 if (err.errMsg && err.errMsg.indexOf('cancel') !== -1) {
												 uni.showToast({
												 	title: '取消支付',
												 	icon: 'none',
													duration: 2500,
													complete: function(res) {
														uni.navigateTo({url: '/pages/my/order-list?status=0'});
													}
												 });
												 
											 }
											 else {
												uni.showToast({
													title: '支付失败，请联系客服处理',
													icon: 'none',
													duration: 2500,
													complete: function(res) {
														uni.navigateTo({url: '/pages/my/order-list?status=0'});
													}
												}); 												
											 }											
										}
									});
								} else {
									uni.hideLoading();
									uni.showToast({
										title: '提交订单失败，请稍后再试',
										icon: 'none'
									});
								}
							})
						}
						else {
							uni.hideLoading();
							uni.showToast({
								title: '下单失败，请稍后再试',
								icon: 'none'
							});
						}
					  })
				  }
				  else {
					  let url = '/pages/tabbar/find/find';
					  uni.navigateTo({url: '/pages/common/login/login?from=' + url})
				  }
				  
			  }
		  },
		  validateForm() {
			  if(this.formData.addressId == null || this.formData.addressId == undefined || this.formData.addressId == 0) {
				  uni.showToast({
				  	title: '请选择收货地址',
				  	icon: 'none'
				  });
				  return false;
			  }
			  if(this.formData.items == null || this.formData.items.length == 0) {
				  uni.showToast({
				  	title: '请选择下单商品后再提交',
				  	icon: 'none'
				  });
				  return false;
			  }
			  return true;
		  },
		  reduceHandle(item) {
			  item.count -= 1;
			  if(item.count == 0) {
				  uni.showToast({
				  	title: '数量必须大于 0',
				  	icon: 'none'
				  });
				  item.count = 1;
			  }
			  else {
				  let _this = this;
				  let data = {id: item.cartId, count: item.count};
				  $H.put('/trade/cart/update-count', data).then(res => {
				  	_this.buildFormData();
				  })
			  }			 
		  },
		  addBuyNumHandle(item) {
			  item.count += 1;
			  let _this = this;
			  let data = {id: item.cartId, count: item.count};
			  $H.put('/trade/cart/update-count', data).then(res => {
			  	 _this.buildFormData();
			  })
		  },
		  parsePrice(price) {
			 return $U.fenToYuan(price);
		  },
		  buildFormData() {
			let _this = this;
			let totalMoney = 0;
			let total = 0;
			let cartItems = [];
			if(this.order && this.order.list) {
				this.order.list.forEach(orchard => {
					if(orchard.items) {
						orchard.items.forEach(item => {
							totalMoney += item.price * item.count;
							let s = {cartId: item.cartId, skuId: item.id, count: item.count};
							cartItems.push(s);
							total ++;
						})
					}
				})
				this.order.totalMoney = totalMoney;
				this.formData.items = cartItems;
				this.formData.total = total;
			}
			
			
			// Object.keys(this.orderItems).forEach(key=>{
			// 	let list = _this.orderItems[key];
			// 	if(list && list.length > 0) {
			// 		list.forEach(item => {
			// 			totalMoney += item.sku.price * item.count;
			// 			total += item.count;
			// 			let s = {cartId: item.id, skuId: item.sku.id, count: item.count};
			// 			cartItems.push(s);
			// 		})
			// 	}			   
			// });
			// this.formData.totalMoney = this.parsePrice(totalMoney);
			// this.formData.total = total;
			// this.formData.items = cartItems;
		  },
		  mapGroupHandle() {
			  if(this.cartList && this.cartList.length > 0) {
				let grouped = {};
				let totalMoney = 0;
				let total = 0;
				this.cartList.forEach(item => {
				  let key = item.orchardId + "_" + item.orchardName;
				  grouped[key] = grouped[key] || [];
				  grouped[key].push(item);
				  totalMoney += item.sku.price * item.count;
				  total += item.count;
				});
				this.orderItems = grouped;
				this.formData.totalMoney = this.parsePrice(totalMoney);
				this.formData.total = total;
			  } 
		  },
		  getOrchardName(key) {
			if(key != '') {
				let groupKey = key.split("_");
				return groupKey[1];
			}
			return '';
		  },
		  getSkuName(properties) {
			  if(properties && properties.length > 0) {
				  let name = ''
				  properties.forEach((p,i) => {
				  	name += p.valueName;
				  	if(i < (properties.length - 1) ) {
				  		name += '、';
				  	}
				  })
				  return name;
			  }
			  return '';
		  },
		  changeAddress() {
			  this.getMyAddressList();
			  this.$refs.addressPopup.open('bottom')	
		  },
		  selectHandle(e) {
			  this.currentAddress = {
			  						  areaId:  e.areaId,
			  						  id:  e.id,
			  						  name: e.name,
			  						  mobile: e.mobile,
			  						  detailAddress: e.detailAddress,
									  defaultStatus: e.defaultStatus
									}
			   this.$refs.addressPopup.close()
			   this.formData.addressId = this.currentAddress.id;
			   this.getSettlement();
		  },
		  getMyAddressList() {
			  let _this = this;
			  $H.get('/member/address/list').then(res => {
			  	 if(res) {
					_this.myAddrList = res;						
				 }
			  })
		  },
		  goAddAddress() {
			  uni.navigateTo({url: '/pages/my/add-address'})	
		  },
		  getDefaultAddress() {
			  let _this = this;
			  $H.get('/member/address/get-default').then(res => {
				  if(res) {
					  _this.currentAddress = {
						  areaId:  res.areaId,
						  id:  res.id,
						  name: res.name,
						  mobile: res.mobile,
						  detailAddress: res.detailAddress,
						  defaultStatus: res.defaultStatus
					  }
				  }
			  })
		  }
		}
	}
</script>

<style lang="scss" scoped>
	.order-detail-page {
		overflow-y: hidden;
		padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
		.order-detail__top {
			padding: 30rpx;
			padding-bottom: 24rpx;
			background: #fff;
			
			.order-detail__top--info {
				height: 42rpx;
				justify-content: space-between;
				align-items: center;
				padding-left: 34rpx;
				
				.name,.phone {
					font-size: 30rpx;
					font-weight: bold;
				}
				.phone {
					margin-left: 30rpx;
				}
			}
			.order-detail__top--address {
				position: relative;
				padding-left: 34rpx;
				margin-top: 14rpx;
				.sprite {
					position: absolute;
					top: 4rpx;
					left: 0;
				}
				.address_icon {
					position: relative;
					top: 4rpx;
					width: 40rpx;
					font-size: 16rpx;
					float: left;
					line-height: 40rpx;
				}
				.address__text {
					line-height: 40rpx;
					font-size: 28rpx;
					// min-width: 550rpx;
				}
			}
			.sprite {
				display: block;
			}
		}
		.order-detail__product {
			margin-top: 16rpx;
			margin-bottom: 16rpx;
			background: #fff;
			
			.shop-name {
				width: 100%;
				height: 40px;
				display: flex;
				align-items: center;
				padding: 0 15px;
				color: #222222;
				font-weight: bold;
				font-size: 15px;
			}
			
			ul {
				padding: 0;
				width: 100%;
			}
			
			li {
				padding: 20rpx 30rpx;
				border-bottom: 1px solid #EBEBEB;
				
				&:last-child {
					border-bottom: none;
				}
			}
			
			.order-detail__product--img {
				width: 180rpx;
				height: 180rpx;
				background: pink;
			}
			.order-detail__product--info {
				position: relative;
				margin-left: 14rpx;
				flex: 1;
				
				.title {
					display: block;
					line-height: 40rpx;
				}
				
				.text__info {
					margin-top: 10rpx;
					font-size: 24rpx;
					line-height: 33rpx;
					color: #666666;
				}
				.order-detail__price {
					position: absolute;
					bottom: 0%;
					width: 100%;
					justify-content: space-between;
					
					.quantity {
						height: 24px;
						
						span {
							display: flex;
							justify-content: center;
							align-items: center;
							width: 24px;
							height: 24px;
						}
						.add,.reduce {
							cursor: pointer;
						}
						.add::before,
						.reduce::before {
							content: '';
							width: 10px;
							height: 2px;
							background: #222222;
							border-radius: 20px;
						}
						.add::after {
							position: absolute;
							content: '';
							width: 2px;
							height: 10px;
							background: #222222;
							border-radius: 20px;
						}
						.number {
							width: 45px;
							background: #F4F4F4;
							font-size: 14px;
							color: #222222;
						}
					}
				}
				.order-detail__product--price {
					align-items: center;
					justify-content: space-between;
					
					.price {
						font-size: 34rpx;
						font-weight: bold;
						color: #FD5052;
						
						.symbol {
							font-size: 24rpx;
							font-weight: normal;
						}
					}
				}
			}
		}
		.order-detail__order {
			margin-top: 16rpx;
			padding: 30rpx;
			background: #fff;
			.flex {
				height: 40rpx;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 32rpx;
				font-size: 28rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
			}
			.label {
				color: #666;
			}
		}
		.notes {
			.notes-title {
				display: block;
				font-size: 14px;
				line-height: 20px;
				margin-bottom: 5px;
			}
			.notes-textarea {
				width: 100%;
				height: 120rpx;
				font-size: 14px;
				background-color: #F4F4F4;
			}
		}
		.order-detail--btns__container {
			width: 100%;
			position: fixed;
			bottom:0;
			left: 0;
			height: calc(env(safe-area-inset-bottom) + 90rpx);
			background: #fff;
		}
		.order-detail--btns {
			width: 100%;
			height: 90rpx;
			background: #fff;
			padding: 8rpx 30rpx;
			border-top: 1px solid #F4F4F4;
			align-items: center;
			justify-content: flex-end;
			box-sizing: border-box;
			
			.total-num {
				font-size: 14px;
				color: #999;
			}
			
			.total-price {
				font-size: 20px;
				color: #FD5052;
				display: flex;
				align-items: center;
				margin: 0 20px;
				font-weight: bold;
				.total-price__text {
					font-size: 14px;
					color: #222222;
					font-weight: normal;
				}
				.symbol {
					font-size: 14px;
					font-weight: normal;
				}
			}
			
			.btn {
				width: auto;
				height: 100%;
				padding: 0 33px;
				align-items: center;
				justify-content: center;
				background: #FD5052;
				color: #fff;
				border-radius: 200px;
			}
		}
		.address_list {
			position: relative;
			width: 100%;
			min-height: 260rpx;
			.add {
				padding: 8rpx 30rpx;
				width: 100%;
				.add-address {
					line-height: 45px;
					border-radius: 200px;
					font-size: 28rpx;
					height: 90rpx;
					align-items: center;
					justify-content: center;
					color: #fff;
					cursor: pointer;
				}
			}			
			.address-detail {
				position: relative;
				width: 100%;
				height: 135rpx;
				float: left;
			}
		}
	}
</style>
